﻿package 
{

	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;

	
	/**
	 * ...
	 * @author hbb
	 */
	public class Main extends Sprite
	{
		
		public function Main():void 
		{
			init();
		}
		
		private function parseAndSend( data:String ):void
		{
			try{
				var info:XiaMiAlbumInfo = albumInfoParser.parser(data);
				info.wiki = layout.input;
				
				var v:URLVariables = new URLVariables();
				info.assign(v);
				
				var r:URLRequest = new URLRequest('http://www.xiami.com/wiki/addalbum');
				r.data = v;
				r.method = URLRequestMethod.POST;
			
				xiamiAlbumLdr.load( r );
			}catch (err:Error) {
				layout.output = err.message;
			}
		}
		
		private function onWebSourceLoadError(e:IOErrorEvent):void 
		{
			layout.output = '加载数据出错';
		}
		
		private function onWebSourceLoadComplete(e:Event):void 
		{
			layout.output = '加载完成，开始分析';
			parseAndSend( webSrcLdr.data as String );
		}
		
		private function onXiamiLoadError(e:IOErrorEvent):void 
		{
			layout.output = '提交数据出错';
		}
		
		private function onXiamiLoadComplete(e:Event):void 
		{
			var data:String = xiamiAlbumLdr.data as String;
			
			if (data.indexOf('谢谢您的提交，我们会尽快处理！') > -1)
			{
				layout.output = '提交成功！';
			}
			else if(data.indexOf('谢谢您的热心，不过这张专辑资料虾米已经有了') > -1)
			{
				layout.output = '已经有了！';
			}
			else
			{
				layout.output = '返回数据错误';
			}
		}
		
		private function init():void
		{
			webSrcLdr.dataFormat = URLLoaderDataFormat.TEXT;
			webSrcLdr.addEventListener(Event.COMPLETE, onWebSourceLoadComplete);
			webSrcLdr.addEventListener(IOErrorEvent.IO_ERROR, onWebSourceLoadError);
			
			xiamiAlbumLdr.dataFormat = URLLoaderDataFormat.TEXT;
			xiamiAlbumLdr.addEventListener(Event.COMPLETE, onXiamiLoadComplete);
			xiamiAlbumLdr.addEventListener(IOErrorEvent.IO_ERROR, onXiamiLoadError);
			
			albumInfoParser = new JapandataTvParser();
			
			layout.clickHandler = loadWebSource;
			addChild(layout);
		}
		
		private function loadWebSource():void
		{
			layout.output = '>> ' + layout.input + '\n加载开始...';
			
			try{
				var r:URLRequest = new URLRequest( layout.input );
				webSrcLdr.load(r);
			}catch (err:Error) {
				layout.output = err.message;
			}
		}
		
		private var webSrcLdr:URLLoader = new URLLoader();
		private var xiamiAlbumLdr:URLLoader = new URLLoader();
		private var albumInfoParser:AlbumInfoParser;
		private var layout:Layout = new Layout();
	}
	
}